(function(window, document) {

window.onload = function() {
	var state = 'wait';

	var iframeElm = document.getElementById('iframe');
	var arrowElm = document.getElementById('arrow');
	var arrow = new Arrow(arrowElm);
	arrow.init();
	
	var wsUrl = "ws://localhost:8182";
	var webSocket = null;

	if(typeof WebSocket != "undefined") {
	    webSocket = new WebSocket(wsUrl);
	}
	else if(typeof MozWebSocket != "undefined") {
	    webSocket = new MozWebSocket(wsUrl);
	}

	if(webSocket) {
		console.log("init");
	    webSocket.onopen = function() {
	    	console.log("opend");
	    	//webSocket.send("open!");
	    };

   		webSocket.onmessage = function(e) {
    		console.log(e.data);
    		messageListener(e.data);
    	};

	    webSocket.onclose = function() {
			console.log("closed...");
	    };
	}
	console.log(webSocket);

	function messageListener(msg) {
		if (msg === "detect") {
    			state = 'detect';
    			arrow.detection();
    			setTimeout(function() {detect();}, 800);
    	} else if (msg === "wait") {
    		state = 'wait';
    		arrow.restart();
    		iframeElm.setAttribute('src', 'frame/thanks.html');
    		setTimeout(function() {restart();}, 3000);
    	} else if (msg === "action" && state === 'detect') {
   			iframeElm.setAttribute('src', '');
   		}
	}

	function restart () {
		if(state === 'wait') {
			//arrow.restart();
			setTransitionTime(arrowElm, 100);
			setTransitionTime(iframeElm, 1000);

			iframeElm.style.cssText += ';opacity: 0.0; -moz-opacity: 0.0; filter:alpha(opacity=0);';
			setTimeout(function() {
				if (state === 'wait') {
					arrowElm.style.cssText += ';opacity: 1.0; -moz-opacity: 1.0; filter:alpha(opacity=10);';
				}
			}, 3000);
			//iframeElm.setAttribute('src', '');
		}
	}

	function detect () {
		if(state === 'detect') {
			setTransitionTime(arrowElm, 100);
			setTransitionTime(iframeElm, 1000);
			arrowElm.style.cssText += ';opacity: 0.0; -moz-opacity: 0.0; filter:alpha(opacity=0);';
			iframeElm.style.cssText += ';opacity: 1.0; -moz-opacity: 1.0; filter:alpha(opacity=10);';
			iframeElm.setAttribute('src', 'frame/hello.html');
		}
	}

	function setTransitionTime(elm, time) {
		elm.style.cssText += ';-webkit-transition-duration: ' + time + 'ms; -moz-transition-duration: ' + time + 'ms; -ms-transition-duration: ' + time + 'ms;';
	}

	var count = 0;
	document.addEventListener("click", function() {
		if (count == 0) {
			messageListener('detect');
		} else if (count == 1) {
			messageListener('action');
		} else {
			messageListener('wait');
			count = -1;
		}
		count += 1;
	}, false);
}

}(window, document));